// pages/orderConfirm/orderConfirm.js
var app = getApp();
const Big = require('../../utils/big.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX: app.globalData.isIphoneX,
    vipInfo: "",
    cursorFlag: 0,
    address: "", // 地址详情
    freightPrice: 0, // 邮费
    goodsCount: 1, // 商品数量
    message: "", // 用户留言
    detail: {}, // 商品详情
    price: '', // 商品单价
    show: false, // 优惠券展示标识
    couponList: [], // 优惠券列表
    couponIndex: '', // 优惠券下标
    selectIndex: '', // 选择优惠券下标
    vipDiscount: 1, // 会员折扣
    couponDiscount: 1, // 优惠券折扣
    couponCount: 0, // 优惠券优惠价格
    drawFlag: '', // 领取红包标识
    boxShow: false, // 红包弹框
  },

  showPopup() {
    this.setData({
      show: true
    });
  },

  onClose() {
    this.setData({
      show: false,
      selectIndex: this.data.couponIndex
    });
  },

  // 增加数量
  addCount() {
    this.setData({
      goodsCount: this.data.goodsCount + 1
    })
    if (this.data.goodsCount > 99) {
      this.setData({
        goodsCount: 99
      })
    }
  },

  // 减少数量
  subCount() {
    if (this.data.goodsCount > 1) {
      this.setData({
        goodsCount: this.data.goodsCount - 1
      })
    }
  },

  bindKeyInput(e) {
    let reg = /^([1-9]\d|\d)$/
    console.log(e.detail.value, reg.test(e.detail.value))
    if (reg.test(e.detail.value)) {
      if (e.detail.value < 1) {
        this.setData({
          goodsCount: 1
        })
      } else if (e.detail.value > 99) {
        this.setData({
          goodsCount: 99
        })
      } else {
        this.setData({
          goodsCount: e.detail.value
        })
      }
    } else {
      if (e.detail.value.length > 1) {
        this.setData({
          goodsCount: '99'
        })
      } else {
        this.setData({
          goodsCount: ''
        })
      }
    }
  },

  bindKeyBlur(e) {
    if (!this.data.goodsCount) {
      this.setData({
        goodsCount: '1'
      })
    }
    if (this.data.goodsCount < 10) {
      // this.setData({
      //   cursorFlag: false
      // })
      // this.setData({
      //   cursorFlag: true
      // })
      this.setData({
        cursorFlag: 0
      })
    }
  },

  // 调整地址列表
  toAddressList() {
    wx.navigateTo({
      url: '../addressList/addressList?fromType=orderConfirm'
    })
  },

  // 获取地址
  getAddress() {
    let that = this
    wx.get("/api/address/list", res => {
      console.log('==== list ===', res)
      if (res.data.length > 0) {
        let index = 0
        try {
          var value = wx.getStorageSync('addressSelect')
          if (value) {
            index = value
          }
        } catch (e) {
          // Do something when catch error
        }
        this.setData({
          address: res.data[index]
        })
        this.chooseAddress()
        wx.removeStorage({
          key: 'addressSelect'
        })
      }
    }, fail => {})
  },

  // 选择订单地址计算邮费
  chooseAddress() {
    wx.get(`/api/orders/chooseAddress/${this.data.address.id}?goodsId=${this.data.detail.id}`, res => {
      console.log('==== chooseAddress ===', res)
      if (res.code == 200) {
        this.setData({
          freightPrice: res.data
        })
      }
    })
  },

  // 备注
  msgInput(e) {
    this.setData({
      message: e.detail.value
    })
  },

  // 选择优惠券
  selectCoupon(e) {
    console.info(index === this.data.selectIndex ? '' : index)
    let index = e.currentTarget.dataset.index
    this.setData({
      selectIndex: index === this.data.selectIndex ? '' : index
    })
  },

  // 确认优惠券
  sureCoupon() {
    this.setData({
      couponIndex: this.data.selectIndex,
      show: false
    })
    this.getCouponCount()
  },

  // 跳转优惠券列表
  toCoupon() {
    wx.setStorage({
      key: "couponFilter",
      data: this.data.detail.goodsProd[this.data.detail.selectFlag],
      success() {
        wx.navigateTo({
          url: '/pages/coupon/coupon?fromPage=orderConfirm'
        })
      }
    })
  },

  submit() {
    if (!this.data.address) {
      wx.showToast({
        title: '请先填写收货地址',
        icon: 'none',
        duration: 2000
      });
      return
    }
    let that = this
    wx.showLoading({
      mask: true
    })
    wx.getSetting({ // 查询订阅消息
      withSubscriptions: true,
      success(res) {
        wx.hideLoading()
        console.log(res.subscriptionsSetting)
        if (res.gzE2MtWOwgmt9F8VdRMMDM8wclsNKQsPoHf5CwLkOTs == 'accept' || res.gzE2MtWOwgmt9F8VdRMMDM8wclsNKQsPoHf5CwLkOTs == 'reject') { // 同意 或 取消
        } else { // 订阅消息 总还是保持以上选择
          wx.requestSubscribeMessage({
            tmplIds: ['gzE2MtWOwgmt9F8VdRMMDM8wclsNKQsPoHf5CwLkOTs', 'UAjyidlquF2Pr_XvZubo7X-rG7dNFffmTw8i_8qrV7k'],
            success(res) {
              console.log(res)
              // if (res.errMsg == 'requestSubscribeMessage:ok') {
              that.orderSubmit();
              // }
            }
          })
        }
      }
    })
  },

  // 提交订单
  orderSubmit() {
    let goodsMoney = this.data.detail.goodsProd[this.data.detail.selectFlag].price * this.data.goodsCount
    goodsMoney = Big(goodsMoney).round(2).toString()
    let orderMoney = this.data.price * this.data.goodsCount * this.data.vipDiscount * this.data.couponDiscount - this.data.couponCount + this.data.freightPrice
    orderMoney = Big(orderMoney).round(2).toString()
    let params = {
      addressId: this.data.address.id, // 用户地址ID
      freightPrice: this.data.freightPrice, // 邮费
      goodsCount: this.data.goodsCount, // 购买数量
      goodsId: this.data.detail.goodsProd[this.data.detail.selectFlag].goodsId, // 商品ID
      goodsMoney: goodsMoney, // 商品总价
      message: this.data.message, // 客户留言
      orderMoney: orderMoney > 0 ? orderMoney : '0.01', // 订单总价
      productId: this.data.detail.goodsProd[this.data.detail.selectFlag].id // 规格ID
    }
    if (this.data.couponList.length > 0 && this.data.couponIndex !== '') {
      params.couponNo = this.data.couponList[this.data.couponIndex].couponNo // 优惠券编号
    }
    if (this.data.detail.userId) {
      params.shareUserId = this.data.detail.userId // 分享人ID
      params.grouponNo = this.data.detail.grouponNo // 团购编码
    }
    console.log('==== submit上传参数 ====', params)
    wx.showLoading({
      mask: true
    })
    wx.post("/api/orders/submit", params, res => {
      console.log('==== submit ===', res)
      wx.get(`/api/orders/prepay?orderNo=${res.data.orderNo}`, result => {
        console.log('==== prepay ===', result)
        if (result.code == 200) {
          this.doWxPay(result)
        }
      })
    }, fail => {})
  },

  //小程序发起微信支付
  doWxPay(param) {
    wx.requestPayment({
      timeStamp: param.data.timeStamp, //记住，这边的timeStamp一定要是字符串类型的，不然会报错
      nonceStr: param.data.nonceStr,
      package: param.data.package,
      signType: param.data.signType,
      paySign: param.data.paySign,
      success(event) {
        console.log('==== success ====', event);
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 1000
        });
      },
      fail(error) {
        console.log('==== error ====', error)
        wx.showToast({
          title: '支付失败',
          icon: 'error',
          duration: 1000
        });
      },
      complete(res) {
        wx.hideLoading()
        console.log("pay complete", res)
        let result = "success"
        if (res.errMsg != 'requestPayment:ok') { // 失败
          result = "fail"
        }
        setTimeout(() => {
          wx.reLaunch({
            url: `/pages/result/result?result=${result}&url=/pages/orderList/orderList`,
          })
        }, 1000);
      }
    });
  },

  // 获取优惠券列表
  getCouponList() {
    wx.get(`${wx.api.couponList}?type=1`, async res => {
      console.info('=== couponList ====', res)
      if (res.code == 200) {
        let shop = this.data.detail.goodsProd[this.data.detail.selectFlag]
        res.data = res.data.filter(item => {
          if ((item.goodsType == '0' || item.goodsType == '2' && item.goodsValue == shop.goodsId) && (item.min == 0 || item.min <= shop.price)) {
            return item
          }
        })
        if (this.data.drawFlag) {
          var drawCoupon = await wx.promisePost("/api/couponUser/sendCoupons", {
            goodsId: this.data.detail.goodsProd[this.data.detail.selectFlag].goodsId,
            grouponNo: this.data.detail.grouponNo
          })
          console.info('==== drawCoupon ====', drawCoupon)
          if (drawCoupon && drawCoupon.code == 200) {
            this.setData({
              couponList: [drawCoupon.data, ...res.data],
              boxShow: true
            })
          } else {
            this.setData({
              couponList: res.data
            })
          }
        } else {
          this.setData({
            couponList: res.data
          })
        }
        this.getCouponCount()
      }
    })
  },

  // 计算优惠券折扣
  getCouponCount() {
    this.setData({
      couponDiscount: 1,
      couponCount: 0
    })
    if (this.data.couponList.length > 0 && this.data.couponIndex !== '') { // 有优惠券
      if (this.data.vipInfo && this.data.vipInfo.level != '0') { // 有会员折扣
        if (this.data.couponList[this.data.couponIndex].type == '3') { // 折扣券
          this.setData({
            couponDiscount: this.data.couponList[this.data.couponIndex].discount
          })
        } else {
          this.setData({
            couponCount: this.data.couponList[this.data.couponIndex].discount
          })
        }

      } else { // 无会员折扣
        if (this.data.couponList[this.data.couponIndex].type == '3') { // 折扣券
          this.setData({
            couponDiscount: this.data.couponList[this.data.couponIndex].discount
          })
        } else {
          this.setData({
            couponCount: this.data.couponList[this.data.couponIndex].discount
          })
        }
      }
    }
  },

  // 关闭红包弹框
  closeBox() {
    this.setData({
      boxShow: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('=== options ====', options)
    this.setData({
      userId: options.userId,
      grouponNo: options.grouponNo,
      drawFlag: options.drawFlag
    })
    console.log(this.data.userId, this.data.grouponNo)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this
    this.setData({
      vipInfo: app.globalData.vipInfo || wx.getStorageSync('vipInfo')
    })
    wx.getStorage({
      key: 'shopDetail',
      success(res) {
        console.log('==== shopDetail ====', res)
        let vipInfo = that.data.vipInfo
        res.data.price = res.data.goodsProd[res.data.selectFlag].price
        that.setData({
          detail: res.data,
          price: res.data.goodsProd[res.data.selectFlag].price,
          vipDiscount: vipInfo.value || 1
        })
        wx.get(wx.api.isLogin, res => {
          console.info('=== isLogin ====', res)
          if (res.code == 200) {
            that.getAddress() // 地址列表
            that.getCouponList() // 优惠券列表
          }
        })

      }
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})